package com.kaichaohulian.baocms.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.kaichaohulian.baocms.R;
import com.kaichaohulian.baocms.activity.SearchActivity;
import com.kaichaohulian.baocms.activity_newcreate.BannerWebViewActivity;
import com.kaichaohulian.baocms.adapter.MyGrid_IndexAdapter;
import com.kaichaohulian.baocms.adapter.NewHotXuqiuAdapter;
import com.kaichaohulian.baocms.adapter.NewXuQiuAdapter;
import com.kaichaohulian.baocms.adapter.PlatFormAdapter;
import com.kaichaohulian.baocms.app.MyApplication;
import com.kaichaohulian.baocms.http.HttpUtil;
import com.kaichaohulian.baocms.http.Url;
import com.kaichaohulian.baocms.newmodel.BannerModel;
import com.kaichaohulian.baocms.newmodel.NewHotModel;
import com.kaichaohulian.baocms.newmodel.NewXuqiuModel;
import com.kaichaohulian.baocms.newmodel.PlatFormModel;
import com.kaichaohulian.baocms.util.FullyLinearLayoutManager;
import com.kaichaohulian.baocms.util.GlideImageLoader;
import com.kaichaohulian.baocms.utils.DBLog;
import com.kaichaohulian.baocms.view.FullyGridLayoutManager;
import com.kaichaohulian.baocms.view.MyGridView;
import com.kaichaohulian.baocms.view.ShowDialog;
import com.kaichaohulian.baocms.view.SimpleDividerItemDecoration;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2015/12/11.
 */
public class HomeFragment2 extends Fragment implements OnBannerListener, OnTabSelectListener {
    private static final java.lang.String TAG = "HomeFragment2";

    public static HomeFragment2 getInstance(MyApplication myApplication, Activity activity, Context context) {
        HomeFragment2 instance = new HomeFragment2();
        Bundle args = new Bundle();
        instance.setArguments(args);
        return instance;

    }


    public HomeFragment2() {

    }


    @BindView(R.id.img_city)
    ImageView imgCity;
    @BindView(R.id.text_city)
    TextView textCity;
    @BindView(R.id.layout_city)
    LinearLayout layoutCity;
    @BindView(R.id.img_search)
    ImageView imgSearch;
    @BindView(R.id.edittext_search)
    EditText edittextSearch;
    @BindView(R.id.layout_search)
    LinearLayout layoutSearch;
    @BindView(R.id.img_right)
    ImageView imgRight;
    @BindView(R.id.banner)
    Banner banner;
    Unbinder unbinder;

    List<String> urls;
    List<String> titles;
    @BindView(R.id.gridview)
    MyGridView gridview;
    PlatFormAdapter platFormAdapter;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    //    最新需求
    @BindView(R.id.recycle_xuqiu)
    RecyclerView recycle_xuqiu;

    //最热需求
    @BindView(R.id.recycle_rexuqiu)
    RecyclerView recycle_rexuqiu;
    List<PlatFormModel> platform;
    private ArrayList<Fragment> mFragments2 = new ArrayList<>();
    //最新需求
    @BindView(R.id.layout_hotnew)
    RelativeLayout layout_hotnew;
    @BindView(R.id.layout_hot_xuqiu)
    RelativeLayout layout_hot_xuqiu;
    @BindView(R.id.img_hotnew)
    ImageView img_hotnew;
    @BindView(R.id.img_zuire)
    ImageView img_zuire;
    @BindView(R.id.bluelines2)
    View bluelines2;
    @BindView(R.id.view_blue1)
    View bluelines1;

    SlidingTabLayout tl2;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    ViewPager viewPager;
    private MyPagerAdapter mAdapter;
    private final String[] mTitles = {
            "最新需求", "最热需求"
    };
    String type;
    String word;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_home_new, null);

        unbinder = ButterKnife.bind(this, view);
        urls = new ArrayList<>();
        titles = new ArrayList<>();
        //平台数据
        platform = new ArrayList<>();
        tl2 = (SlidingTabLayout) view.findViewById(R.id.tl_2);
        tl2.setOnTabSelectListener(this);
        viewPager = (ViewPager) view.findViewById(R.id.viewPager);
        getnewXuqiu();
        for (String title : mTitles) {
            mFragments.add(SimpleCardFragment.getInstance(title));
        }
        getBannerData();
        getplatFormData();
        gethotXuqiu();
        mAdapter = new MyPagerAdapter(getFragmentManager());
        viewPager.setAdapter(mAdapter);
        tl2.setViewPager(viewPager);

        img_hotnew.setImageResource(R.mipmap.newxuqiu_selected);
        recycle_xuqiu.setLayoutManager(new FullyLinearLayoutManager(getActivity()));
        gridview.setAdapter(new MyGrid_IndexAdapter(getActivity()));
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });
        recyclerView.setLayoutManager(new FullyGridLayoutManager(getActivity(), 2));

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);

                switch (i) {
                    case 0:
                        type = "2";
//                        word = "帮我取";
                        word = "";
                        break;
                    case 1:
//                        startActivity(new Intent(getActivity(), HelpGetActivity.class));
                        type = "1";
//                        word = "帮我买";
                        word = "";
                        break;

                    case 2:
//                        startActivity(new Intent(getActivity(), HelpGiveActivity.class));
                        type = "3";
//                        word = "帮我送";
                        word = "";
                        break;
                    case 3:
//                        startActivity(new Intent(getActivity(), DaiGouActivity.class));
                        type = "8";
//                        word = "异地代购";
                        word = "";
                        break;
                    case 4:
//                        startActivity(new Intent(getActivity(), GongXiangXZActivity.class));
                        type = "10";
//                        word = "共享闲置";
                        word = "";
                        break;
                    case 5:
//                        startActivity(new Intent(getActivity(), PaiDuiActivity.class));
                        type = "5";
//                        word = "排队";
                        word = "";
                        break;
                    case 6:
//                        startActivity(new Intent(getActivity(), YuYueActivity.class));
                        type = "9";
                        word = "";
                        break;
                    case 7:
//                        startActivity(new Intent(getActivity(), ShunFengCheActivity.class));
                        type = "7";
//                        word = "顺风车";
                        word = "";
                        break;
                    case 8:
//                        startActivity(new Intent(getActivity(), YuYueActivity.class));

                        type = "6";
//                        word = "其他需求 ";
                        word = "";
                        break;
                    case 9:
//                        startActivity(new Intent(getActivity(), YuYueActivity.class));
                        //发布服务
                        type = "4";
//                        word = "预约";
                        word = "";
                        break;

                }
                intent.putExtra("type", type);
                intent.putExtra("word", word);
                startActivity(intent);
            }
        });

//进入搜索页面


        return view;
    }


    public void getBannerData() {

        final RequestParams params = new RequestParams();


        HttpUtil.post(Url.index_Banner, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                Log.d(response.toString(), "333333333333333333");
                try {

                    BannerModel bannerModel = new BannerModel();

                    Gson gson = new Gson();
                    bannerModel = gson.fromJson(response.toString(), BannerModel.class);

                    for (int i = 0; i < bannerModel.getDataObject().size(); i++) {
                        urls.add(bannerModel.getDataObject().get(i).getPicUrl());
                    }
                    for (int i = 0; i < bannerModel.getDataObject().size(); i++) {
                        titles.add(bannerModel.getDataObject().get(i).getTitle());
                    }


                    banner.isAutoPlay(true);
                    //设置轮播时间
                    banner.setDelayTime(2000);
                    //设置指示器位置（当banner模式中有指示器时）
                    banner.setIndicatorGravity(BannerConfig.CENTER);

                    //banner设置方法全部调用完毕时最后调用
                    banner.start();
                    banner.setDelayTime(2000);
                    //设置指示器位置（当banner模式中有指示器时）
                    banner.setIndicatorGravity(BannerConfig.CENTER);
                    banner.setImages(urls)
                            .setImageLoader(new GlideImageLoader())
                            .setOnBannerListener(new OnBannerListener() {
                                @Override
                                public void OnBannerClick(int position) {
//                                    Toast.makeText(getActivity(), "你点击了：" + position, Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(getActivity(), BannerWebViewActivity.class);
                                    intent.putExtra("url", urls.get(position));
                                    intent.putExtra("title", titles.get(position));
                                    startActivity(intent);

                                }
                            })
                            .start();


                    Log.d(params.toString(), "1111111111111111111111111111");
                    Log.d(params.toString(), "1111111111111111111111111111");
                    Log.d(params.toString(), "1111111111111111111111111111");

                    ShowDialog.dissmiss();
                } catch (Exception e) {

                }

            }

            @Override
            public void onFinish() {
                ShowDialog.dissmiss();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                DBLog.e("tag", statusCode + ":" + responseString);
                ShowDialog.dissmiss();
//                Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
//                Toast.makeText(getActivity(), "请求取消", Toast.LENGTH_SHORT).show();
            }
        });

    }


    public void getplatFormData() {


        final RequestParams params = new RequestParams();
        params.put("page", 1);

        HttpUtil.post(Url.platForm, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                Log.d(response.toString(), "333333333333333");
                PlatFormModel platFormModel = new PlatFormModel();
                Gson gson = new Gson();
                platFormModel = gson.fromJson(response.toString(), PlatFormModel.class);

                platFormAdapter = new PlatFormAdapter(platFormModel.getDataObject());
                //   mIndexAdapter = new IndexAdapter(mDatas);

                try {
                    Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.line_divider_index);
                    recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getContext(), drawable, 2));
                    recyclerView.setAdapter(platFormAdapter);
                    ShowDialog.dissmiss();
                } catch (Exception e) {

                }


            }

            @Override
            public void onFinish() {
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                DBLog.e("tag", statusCode + ":" + responseString);
                ShowDialog.dissmiss();

            }

            @Override
            public void onCancel() {
//                Toast.makeText(getActivity(), "请求取消", Toast.LENGTH_SHORT).show();
                ShowDialog.dissmiss();
            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick({R.id.img_city, R.id.text_city, R.id.layout_city, R.id.img_search, R.id.edittext_search, R.id.layout_search, R.id.img_right, R.id.banner, R.id.layout_hotnew, R.id.layout_hot_xuqiu, R.id.img_hotnew, R.id.img_zuire})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_city:
                break;
            case R.id.text_city:
                break;
            case R.id.layout_city:
                break;
            case R.id.img_search:
                break;
            case R.id.edittext_search:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;
            case R.id.layout_search:
                startActivity(new Intent(getActivity(), SearchActivity.class));

                break;
            case R.id.img_right:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;
            case R.id.banner:
                break;

//            R.id.layoutotnew,R.id.layout_hot_xuqiu
            //最新需求
            case R.id.layout_hotnew:
                img_hotnew.setImageResource(R.mipmap.newxuqiu_selected);
                img_zuire.setImageResource(R.mipmap.zuire);
                bluelines1.setVisibility(View.VISIBLE);
                bluelines2.setVisibility(View.GONE);

                getnewXuqiu();
                recycle_rexuqiu.setVisibility(View.VISIBLE);
                recycle_xuqiu.setVisibility(View.GONE);
                break;
            //最新需求
            case R.id.img_hotnew:
                img_hotnew.setImageResource(R.mipmap.newxuqiu_selected);
                img_zuire.setImageResource(R.mipmap.zuire);
                bluelines1.setVisibility(View.VISIBLE);
                bluelines2.setVisibility(View.GONE);

                getnewXuqiu();
                recycle_rexuqiu.setVisibility(View.VISIBLE);
                recycle_xuqiu.setVisibility(View.GONE);
                break;
//最热需求
            case R.id.layout_hot_xuqiu:
                img_hotnew.setImageResource(R.mipmap.newxuqiu_unselected);
                img_zuire.setImageResource(R.mipmap.newzuire_selected);
                bluelines1.setVisibility(View.GONE);
                bluelines2.setVisibility(View.VISIBLE);
                recycle_rexuqiu.setVisibility(View.GONE);
                recycle_xuqiu.setVisibility(View.VISIBLE);

                gethotXuqiu();
                break;

            //最热需求
            case R.id.img_zuire:
                img_hotnew.setImageResource(R.mipmap.newxuqiu_unselected);
                img_zuire.setImageResource(R.mipmap.newzuire_selected);
                bluelines1.setVisibility(View.GONE);
                bluelines2.setVisibility(View.VISIBLE);
                recycle_rexuqiu.setVisibility(View.GONE);
                recycle_xuqiu.setVisibility(View.VISIBLE);

                gethotXuqiu();
                break;


        }
    }

    //    最新需求
    List<NewXuqiuModel.DataObjectBean> newXuqiuModelList = new ArrayList<>();

    public void getnewXuqiu() {

        final RequestParams params = new RequestParams();
        params.put("page", 1);

        HttpUtil.post(Url.newxuqiu, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                Log.d(response.toString(), "333333333333333");
                NewXuqiuModel newXuqiuModel = new NewXuqiuModel();
                Gson gson = new Gson();
                newXuqiuModel = gson.fromJson(response.toString(), NewXuqiuModel.class);
                newXuqiuModelList = newXuqiuModel.getDataObject();
                try {
                    recycle_rexuqiu.setLayoutManager(new FullyLinearLayoutManager(getActivity()));

                    NewXuQiuAdapter newXuQiuAdapter = new NewXuQiuAdapter(newXuqiuModelList);
                    Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.line_divider);
//                recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getContext(), drawable, 2));
                    recycle_rexuqiu.setAdapter(newXuQiuAdapter);
                } catch (Exception e) {

                }


            }

            @Override
            public void onFinish() {
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                DBLog.e("tag", statusCode + ":" + responseString);
                ShowDialog.dissmiss();

            }

            @Override
            public void onCancel() {
//                Toast.makeText(getActivity(), "请求取消", Toast.LENGTH_SHORT).show();
                ShowDialog.dissmiss();
            }
        });
    }

    //最热需求
    List<NewHotModel.DataObjectBean> newhtDataBean = new ArrayList<>();

    public void gethotXuqiu() {

        final RequestParams params = new RequestParams();
        params.put("page", 1);

        HttpUtil.post(Url.newhotxuqiu, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    Log.d(response.toString(), "333333333333333");
                    NewHotModel newXuqiuModel = new NewHotModel();
                    Gson gson = new Gson();
                    newXuqiuModel = gson.fromJson(response.toString(), NewHotModel.class);
//                recycle_xuqiu.setLayoutManager(new Full(getActivity(), 2));
//                recycle_xuqiu.setLayoutManager(new LinearLayoutManager(getActivity()));
                    newhtDataBean = newXuqiuModel.getDataObject();
                    NewHotXuqiuAdapter newXuQiuAdapter = new NewHotXuqiuAdapter(newhtDataBean);


                    Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.line_divider);
                    recycle_xuqiu.addItemDecoration(new SimpleDividerItemDecoration(getContext(), drawable, 2));
                    recycle_xuqiu.setAdapter(newXuQiuAdapter);
                } catch (Exception e) {
                    e.getMessage();
                }


            }

            @Override
            public void onFinish() {
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                DBLog.e("tag", statusCode + ":" + responseString);
                ShowDialog.dissmiss();

            }

            @Override
            public void onCancel() {
//                Toast.makeText(getActivity(), "请求取消", Toast.LENGTH_SHORT).show();
                ShowDialog.dissmiss();
            }
        });
    }

    @Override
    public void OnBannerClick(int position) {
//        Toast.makeText(getActivity(), "你点击了：" + position, Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(getActivity(), BannerWebViewActivity.class);
        intent.putExtra("url", urls.get(position));
        intent.putExtra("title", titles.get(position));
        startActivity(intent);

    }


    @Override
    public void onTabSelect(int position) {
        Toast.makeText(getActivity(), "onTabSelect&position--->" + position, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onTabReselect(int position) {
//        Toast.makeText(getActivity(), "onTabReselect&position--->" + position, Toast.LENGTH_SHORT).show();


    }


    //最热需求
    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    }
}
